<?php

class Installer {

	public function __construct() {
		if ( $this->isStep(3) && !$this->isInstalled() ) {
			$this->install();
		}
	}
	
	/**
	 * Returns the current step
	 */
	public function getStep() {
		$step = intval($_POST['step']);
		if ( $step < 1 ) {
			$step = 1;
		}
		return $step;
	}
	public function isStep($step) {
		return ( $this->getStep() === $step );
	}
	
	/**
	 * Returns true if the Cinnamon is already be configured
	 */
	public function isConfigured() {
		return file_exists( dirname(dirname(__FILE__)) .'/cse-config.php' );
	}
	
	/**
	 * Returns true if is the configuration file is writable
	 */
	public function isConfigurable() {
		return ( file_exists( dirname(dirname(__FILE__)) .'/cse-config-sample.php' ) &&
				 is_writable( dirname(dirname(__FILE__)) ) );
	}
	
	/**
	 * Returns true if the Cinnamon is already installed
	 */
	public function isInstalled() {
		if ( !$this->isConfigured() ) {
			return false;
		}
		
		require_once dirname(dirname(__FILE__)) .'/cse-config.php';
		require_once dirname(dirname(__FILE__)) .'/core/DatabaseAdapter.php';
		$db = new DatabaseAdapter(CSEDB_USER, CSEDB_PASS, CSEDB_HOST, CSEDB_NAME);
		
		try {
			$numOfOptions = $db->getValue('SELECT COUNT(*) FROM '. $db->options);		
			$numOfOptions = (int) $numOfOptions;
		} catch ( Exception $e ) {
			return false;
		}		
		
		return ( $numOfOptions > 0 );
	}
	
	public function getVersion() {
		return '0.5.8';
	}
	
	public function install() {
		global $auth;
		
		// try to create cse-config.php file
		if ( !$this->isConfigured() && $this->isConfigurable() ) {
			// get post params
			$params = null;
			$params->csedb_user = trim($_POST['csedb_username']);
			$params->csedb_pass = trim($_POST['csedb_password']);
			$params->csedb_host = trim($_POST['csedb_host']);
			$params->csedb_name = trim($_POST['csedb_database']);
			$params->csedb_prefix = trim($_POST['csedb_prefix']);
			
			// try to connect to database
			require_once dirname(dirname(__FILE__)) .'/core/DatabaseAdapter.php';
			try {
				$db = new DatabaseAdapter($params->csedb_user, $params->csedb_pass, $params->csedb_host, $params->csedb_name);		
			} catch ( Exception $e ) {
				die('<p>Unable to connect to database. Please check your configuration settings.</p>');
			}	
		
			$sample = file(dirname(dirname(__FILE__)) .'/cse-config-sample.php'); 
			$config = fopen(dirname(dirname(__FILE__)) .'/cse-config.php', 'w');

		    foreach ( $sample as $num=>$line ) {
				if ( preg_match("/^define\('(CSEDB_[A-Z]+)', '([^']*)'\)/", $line, $matches) ) {
					$line = str_replace("'". $matches[2] ."'", "'". $params->{strtolower($matches[1])} ."'", $line); 
				}
				fwrite($config, $line);
			}
			fclose($config);
		} 
		
		if ( !$this->isConfigured() ) {
			die('<p>Failed to create <code>cse-config.php</code> file. You should create it by your own.</p>');
		}
		
		// load configuration file
		require_once dirname(dirname(__FILE__)) .'/cse-init.php';	
		if ( !isset($db) ) {
			$db = new DatabaseAdapter(CSEDB_USER, CSEDB_PASS, CSEDB_HOST, CSEDB_NAME);
		}
		
		// create tables
		$sql = "CREATE TABLE ". $db->sites ." ( "
			  ."site_id int(10) unsigned NOT NULL auto_increment, "
			  ."site_url varchar(255) NOT NULL default '', "
  			  ."site_name varchar(255) NOT NULL default '', "
			  ."ignore_www ENUM('y','n') NOT NULL DEFAULT 'y', "
			  ."match_subdomains ENUM('y','n') NOT NULL DEFAULT 'n', "			  
			  ."utc_offset smallint(6) NOT NULL default '0', "
			  ."has_code enum('y','n') NOT NULL default 'n', "			  
			  ."PRIMARY KEY  (site_id), "
			  ."UNIQUE KEY site_url (site_url) "
			  .")";
		$db->query($sql);

		$sql = "CREATE TABLE ". $db->requests ." ( "
 			  ."request_id int(10) unsigned NOT NULL auto_increment, "
			  ."request_type varchar(20) NOT NULL default '', "
			  ."request_url varchar(250) NOT NULL default '', "
			  ."request_title varchar(250) NOT NULL, "
			  ."request_datetime datetime NOT NULL default '0000-00-00 00:00:00', "
			  ."request_utc_datetime datetime NOT NULL, "
			  ."visit_id varchar(40) NOT NULL, "
			  ."ip_address varchar(15) NOT NULL default '', "
			  ."site_id int(10) unsigned NOT NULL default '0', "
			  ."PRIMARY KEY  (request_id), "
			  ."KEY site_id (site_id), "
			  ."KEY request_datetime (request_datetime) "
			  .")";
		$db->query($sql);
			  
		$sql = "CREATE TABLE ". $db->options ." ( "
			  ."option_id int(10) unsigned NOT NULL auto_increment, "
			  ."option_name varchar(100) NOT NULL default '', "
			  ."option_value text NOT NULL, "
			  ."option_autoload enum('y','n') NOT NULL default 'y', "
			  ."PRIMARY KEY (option_id), "
			  ."KEY option_name (option_name) "
			  .")"; 	
		$db->query($sql);	
		
		// add configuration 
		$auth->email = trim($_POST['cseauth_email']);
		$auth->login = 'admin';
		$auth->pass	 = substr(md5(uniqid(rand(), true)), 0, 6);

		$db->query("INSERT INTO ". $db->options ." VALUES (NULL, 'auth.login', 'admin', 'y')");
		$db->query("INSERT INTO ". $db->options ." VALUES (NULL, 'auth.pass', '". md5($auth->pass) ."', 'y')");
		$db->query("INSERT INTO ". $db->options ." VALUES (NULL, 'auth.email', '". $auth->email ."', 'n')");
		$db->query("INSERT INTO ". $db->options ." VALUES (NULL, 'auth.required', 'y', 'y')");
		$db->query("INSERT INTO ". $db->options ." VALUES (NULL, 'plugins.enabled', 'a:0:{}', 'y')");
		$db->query("INSERT INTO ". $db->options ." VALUES (NULL, 'date.format', 'relative', 'y')");	
		$db->query("INSERT INTO ". $db->options ." VALUES (NULL, 'date.custom', 'M j, Y h:i a', 'y')");
		$db->query("INSERT INTO ". $db->options ." VALUES (NULL, 'cse.version', '". $this->getVersion() ."', 'y')");
		
		// analyze url
		$cseurl = parse_url(CSEURL);
		
		// add the first site
		$site = new stdClass();
		$site->url = ( strlen($cseurl['path']) > 1 ) ? $cseurl['host'] : preg_replace('!^[^.]+\.!', '', $cseurl['host']);
		$site->url = $cseurl['scheme'] .'://'. $site->url;
		if ( !empty($cseurl['port']) && strcmp($cseurl['port'], '80') != 0 )
			$site->cseurl = $site->cseurl .':'. $cseurl['port'];
		$site->title = preg_replace('!^www\.!i', '', $cseurl['host']);
		unset($cseurl);

		$db->query("INSERT INTO ". $db->sites ." VALUES(NULL, '". $site->url ."', '". $site->title ."', 'y', 'n', 0, 'n')");
						
		
		// send an email including login details
		$headers = 'From: the Cinnamon <thecinnamon@' . $_SERVER['SERVER_NAME'] . '>'
				  .'X-Mailer: PHP v'. phpversion();
		$message = 'Congratulations! Cinnamon has been successfully installed at '. CSEURL ."\n"
				  .'You can login at '. CSEURL .'/cse-login.php using the following details:'."\n"
				  ."\t".'Username: '. $auth->login ."\n"
				  ."\t".'Password: '. $auth->pass ."\n\n"
				  .'Thank you for using Cinnamon Statistics Engine!'."\n\n"
				  .'-- The Cinnamon Statistics Engine Team';
		@mail($auth->email, 'Installation Completed', $message, $headers);
	}
}

?>